//
//  UIButton+Extension.swift
//  PigManager
//
//  Created by 邱仙凯 on 2020/9/23.
//  Copyright © 2020 Much. All rights reserved.
//

import Foundation
import UIKit

extension UIButton {
    
    var indexP: IndexPath {
        set {
            objc_setAssociatedObject(self, &AssociatedBtnKeys.testNameKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        
        get {
            return (objc_getAssociatedObject(self, &AssociatedBtnKeys.testNameKey) as? IndexPath)!
        }
    }
 
    convenience init(title: String?, imageName: String?, target: AnyObject?, selector: Selector?, font: UIFont?, titleColor: UIColor?) {
        self.init()

        setTitleColor(titleColor, for: UIControl.State())
        titleLabel?.font = font
        setTitle(title, for: UIControl.State())

        if let tempImage = imageName {
            setImage(UIImage(named: tempImage), for: UIControl.State())
        }

        if let tempSelector = selector {
            addTarget(target, action: tempSelector, for: .touchUpInside)
        }
    }
    
    //  给barbuttonitem 使用
    static func creat4Item(title:String,color:UIColor = .black,action:@escaping BtnAction) -> UIButton {
         let b = UIButton()
        b.setTitle(title, for: .normal)
        b.setTitleColor(color, for: .normal)
        b.addTouchUpInSideAction { btn in
            action(btn)
        }
        return b
    }
    //  给barbuttonitem 使用
    static func creat4Item(image:UIImage?,action:@escaping BtnAction) -> UIButton {
         let b = UIButton()
        b.setBackgroundImage(image, for: .normal)
        b.addTouchUpInSideAction { btn in
            action(btn)
        }
        return b
    }
    
    

}



// 扩大点击范围的button
class BigRangeButton:UIButton {
    let buttonInset:CGFloat = 10
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let newArea = CGRect(x:self.bounds.origin.x - buttonInset,y: self.bounds.origin.y - buttonInset,width: self.bounds.size.width + buttonInset * 2, height:self.bounds.size.height + buttonInset * 2)
        return newArea.contains(point)
    }
}
typealias BtnAction = (UIButton)->()

extension UIButton {

///  gei button 添加一个属性 用于记录点击tag
   private struct AssociatedBtnKeys{
      static var actionKey = "actionKey"
       static var testNameKey = "testNameKey"
 
   }
    // 设置两次点击之间的最小时间间隔（例如，0.5秒）
    static let minimumTimeInterval: TimeInterval = 1.0
    
    @objc dynamic var actionDic: NSMutableDictionary? {
        set{
            objc_setAssociatedObject(self,&AssociatedBtnKeys.actionKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
        }
        get{
            if let dic = objc_getAssociatedObject(self, &AssociatedBtnKeys.actionKey) as? NSDictionary{
                return NSMutableDictionary.init(dictionary: dic)
            }
            return nil
        }
    }
   
    
   
    
    
     
    
    @objc dynamic fileprivate func DIY_button_add(action:@escaping  BtnAction ,for controlEvents: UIControl.Event) {
        let eventStr = NSString.init(string: String.init(describing: controlEvents.rawValue))
        if let actions = self.actionDic {
            actions.setObject(action, forKey: eventStr)
            self.actionDic = actions
        }else{
            self.actionDic = NSMutableDictionary.init(object: action, forKey: eventStr)
        }
        
        switch controlEvents {
            case .touchUpInside:
 
            self.addTarget(self, action: #selector(touchUpInSideBtnAction), for: .touchUpInside)

            case .touchUpOutside:
                self.addTarget(self, action: #selector(touchUpOutsideBtnAction), for: .touchUpOutside)
        default:
            break
         }
      }
// 按钮事件传递给闭包
      @objc fileprivate func touchUpInSideBtnAction(btn: UIButton) {
          
 
          
          if let actionDic = self.actionDic  {
              if let touchUpInSideAction = actionDic.object(forKey: String.init(describing: UIControl.Event.touchUpInside.rawValue)) as? BtnAction {
                  touchUpInSideAction(self)
               }
          }
      }

      @objc fileprivate func touchUpOutsideBtnAction(btn: UIButton) {
         if let actionDic = self.actionDic  {
             if let touchUpOutsideBtnAction = actionDic.object(forKey:   String.init(describing: UIControl.Event.touchUpOutside.rawValue)) as? BtnAction{
                touchUpOutsideBtnAction(self)
            }
         }
      }
    
     @discardableResult
      func addTouchUpInSideAction(_ action:@escaping BtnAction) -> UIButton{
          self.DIY_button_add(action: action, for: .touchUpInside)
          return self
      }
      @discardableResult
      func addTouchUpOutSideBtnAction(_ action:@escaping BtnAction) -> UIButton{
              self.DIY_button_add(action: action, for: .touchUpOutside)
             return self
      }
   }

 
typealias TapAction = (UITapGestureRecognizer)->()

extension UITapGestureRecognizer {
    private struct AssociatetapdKeys{
        static var actionKey = "actiontapKey"
    }
    @objc dynamic var action: TapAction? {
        set{
            objc_setAssociatedObject(self,&AssociatetapdKeys.actionKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
        }
        get{
            if let action = objc_getAssociatedObject(self, &AssociatetapdKeys.actionKey) as? TapAction {
                return action
            }
            return nil
        }
    }
 
    func addTap(_ action:@escaping  TapAction) {
        self.action = action
         self.addTarget(self, action: #selector(touchTapAction))
    }
     @objc func touchTapAction(tap: UITapGestureRecognizer) {
         if let action = self.action {
             action(tap)
         }
    }
}



typealias SegmentChangeAction = (UISegmentedControl)->()

extension UISegmentedControl {
    private struct AssociatetapdKeys{
        static var actionKey = "actiontapKey"
    }
    @objc dynamic var action: SegmentChangeAction? {
        set{
            objc_setAssociatedObject(self,&AssociatetapdKeys.actionKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
        }
        get{
            if let action = objc_getAssociatedObject(self, &AssociatetapdKeys.actionKey) as? SegmentChangeAction {
                return action
            }
            return nil
        }
    }
 
    func addSegmentChangeClosure(_ action:@escaping  SegmentChangeAction) {
        self.action = action
        self.addTarget(self, action: #selector(segmentChangeAction(segment:)), for: .valueChanged)
      }
    @objc func segmentChangeAction(segment: UISegmentedControl) {
         if let action = self.action {
             action(segment)
         }
    }
}

  
typealias SwitchChangeAction = (UISwitch)->()

extension UISwitch {
    private struct AssociatetapdKeys{
        static var actionKey = "actiontapKey"
    }
    @objc dynamic var action: SwitchChangeAction? {
        set{
            objc_setAssociatedObject(self,&AssociatetapdKeys.actionKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
        }
        get{
            if let action = objc_getAssociatedObject(self, &AssociatetapdKeys.actionKey) as? SwitchChangeAction {
                return action
            }
            return nil
        }
    }
    
    func addSwitchChangeClosure(_ action:@escaping  SwitchChangeAction) {
        self.action = action
        self.addTarget(self, action: #selector(switchChangeAction(switchx:)), for: .valueChanged)
      }
    @objc func switchChangeAction(switchx: UISwitch) {
         if let action = self.action {
             action(switchx)
         }
    }
 }
